package com.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db.DB;
import com.tools.Constants;

public class C2S10professional extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {
		Constants.init();
		System.out.println("DB name:" + Constants.DBNAME);
		DB.connDB();
		super.init();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb10] whitebox10 get begin");
		System.out.println("版本>= 17");
		PrintWriter writer = response.getWriter();

		String user_id = null;
		String pro_id = null;
		String cmd = null;

		while (er.hasMoreElements()) {
			String element = er.nextElement();
			if (element.equals("user_id")) {
				user_id = request.getParameterValues("user_id")[0];
				System.out.println("[vswb10] user_id:" + user_id);
			}
			if (element.equals("pro_id")) {
				pro_id = request.getParameterValues("pro_id")[0];
				System.out.println("[vswb10] pro_id:" + pro_id);
			}
			if (element.equals("cmd")) {
				cmd = request.getParameterValues("cmd")[0];
				System.out.println("[vswb10] cmd:" + cmd);
			}
		}
		if ((user_id != null) && (cmd != null) && (cmd.equals("read"))) {
			String professional = null;
			ResultSet rs = DB.select("select * from userinfo where user_id='" + user_id + "';");
			try {
				while (rs.next()) {
					professional = rs.getString("professional");
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (professional == null) {
				writer.println("nobody");
				System.out.println("user " + user_id + "read the professional,and the gay is nobody");
			} else {
				writer.println(professional);
				System.out.println("user " + user_id + "read the professional,and the gay is " + professional);
			}
		}
		if ((user_id != null) && (pro_id != null) && (cmd != null) && (cmd.equals("write"))) {
			DB.update("update userinfo set professional='"+pro_id+"' where user_id='"+user_id+"';");
			DB.update("update userinfo set time=now() where user_id='"+user_id+"';");
			writer.println(pro_id);
			System.out.println("user write the professional");
		}
	}
}
